from rest_framework import serializers
from ..models.quantityModel import *
from ..config.message_config import Search_message, Search_message_type
from ..utils.related_util.content_util import get_units_by_quantity
from ..utils.related_util.choice_util import get_value_from_map

class QuantityListQuerySerializer(serializers.Serializer):
    quantity_name = serializers.CharField(
        required=False, allow_blank=True)
    sei_id = serializers.CharField(
        required=False, allow_blank=True)
    quantity_symbol = serializers.CharField(
        required=False, allow_blank=True)
    dimension = serializers.JSONField(required=False)
    page_size = serializers.IntegerField(
        required=False, max_value=50, min_value=1)
    current_page = serializers.IntegerField(required=False)
    sort_prop = serializers.CharField(required=False, allow_blank=True)
    sort_order = serializers.CharField(required=False, allow_blank=True)

    def validate(self, attrs):
        filter_flag = True
        page_flag = True
        if "quantity_name" in attrs:
            attrs["quantity_name"] = attrs["quantity_name"].strip()
            if attrs["quantity_name"] == "":
                attrs.pop("quantity_name")
        if "sei_id" in attrs:
            attrs["sei_id"] = attrs["sei_id"].strip()
            if attrs["sei_id"] == "":
                attrs.pop("sei_id")
        if "quantity_symbol" in attrs:
            attrs["quantity_symbol"] = attrs["quantity_symbol"].strip()
            if attrs["quantity_symbol"] == "":
                attrs.pop("quantity_symbol")
        if "dimension" in attrs:
            if len(attrs["dimension"]) == 0:
                attrs.pop("dimension")
            else:
                attrs["dimension"] = attrs["dimension"][0]
        if ("quantity_name" not in attrs or attrs["quantity_name"] == "") and ("sei_id" not in attrs or attrs["sei_id"] == "") and ("quantity_symbol" not in attrs or attrs["quantity_symbol"] == "") and ("dimension" not in attrs or attrs["dimension"] == ""):
            filter_flag = False
        if ("page_size" not in attrs):
            page_flag = False
        if not filter_flag and not page_flag:
            raise serializers.ValidationError({
                'detail': "{} : {}".format(Search_message_type.get("SEARCH_FAIL"), Search_message.get("SEARCH_BROAD"))
            })
        try:
            attrs = super().validate(attrs)
        except serializers.ValidationError as e:
            raise serializers.ValidationError({
                'detail': "{} : {}".format(Search_message_type.get("SEARCH_FAIL"), str(e.detail))
            })
        return attrs

    @classmethod
    def get_query_fields(self):
        return [{"title": "量名称：", "dataIndex": "quantity_name", "type": "CharField"},
                {"title": "量编码：", "dataIndex": "sei_id", "type": "CharField"},
                {"title": "量符号：", "dataIndex": "quantity_symbol", "type": "CharField"},
                {"title": "量纲：", "dataIndex": "dimension", "type": "CharField"}]


class QuantityListSerializer(serializers.ModelSerializer):
    quantity_name = serializers.SerializerMethodField()
    dimension = serializers.SerializerMethodField()
    available_units = serializers.SerializerMethodField()

    class Meta:
        model = Quantity
        fields = ['uuid', 'quantity_name', 'sei_id', 'quantity_symbol',
                  'dimension', 'available_units', 'quantity_description', 'quantity_comment']

    def get_quantity_name(self, obj):
        return obj.show_full_name()
    
    def get_dimension(self, obj):
        return obj.dimension.show_short_name()

    def get_available_units(self, obj):
        unit_content = []
        unit_list = get_units_by_quantity(obj)
        for unit in unit_list:
            unit_content.append("{}({})".format(
                unit.show_short_name(), unit.unit_symbol))
        if len(unit_content) == 0:
            return "无"
        return " ; ".join(unit_content)

    @classmethod
    def get_extra_fields_info(self):
        return [{"dataIndex":"quantity_name","title":"量名称","type":"TextField"},
            {"dataIndex": "available_units", "title": "可用单位", "type": "TextField"},]


class QuantityCreateSerializer(serializers.ModelSerializer):
    dimension = serializers.JSONField()
    quantity_type = serializers.JSONField()

    class Meta:
        model = Quantity
        fields = ['quantity_name', 'quantity_name_en', 'sei_id', 'quantity_symbol','quantity_abbreviation', 'quantity_type',
                  'dimension', 'quantity_description', 'quantity_description_en', 'quantity_comment']

    def to_internal_value(self, data):
        data = super().to_internal_value(data)
        for field_name in self.fields:
            value = data.get(field_name)
            if isinstance(value, str):
                data[field_name] = value.strip()

        return data
    
    def validate(self, attrs):
        if "dimension" in attrs:
            if len(attrs["dimension"]) == 0:
                attrs.pop("dimension")
            else:
                attrs["dimension"] = attrs["dimension"][0]
        if "quantity_type" in attrs:
            if len(attrs["quantity_type"]) == 0:
                attrs.pop("quantity_type")
            else:
                attrs["quantity_type"] = attrs["quantity_type"][0]
        try:
            attrs = super().validate(attrs)
        except serializers.ValidationError as e:
            raise serializers.ValidationError(str(e))
        return attrs


class QuantityModifyInfoSerializer(serializers.ModelSerializer):

    class Meta:
        model = Quantity
        fields = ['quantity_name', 'quantity_name_en', 'sei_id', 'quantity_symbol','quantity_abbreviation', 'quantity_type',
                  'dimension', 'quantity_description', 'quantity_description_en', 'quantity_comment']


class QuantityModifyInfoInSerializer(serializers.ModelSerializer):
    dimension = serializers.JSONField()
    quantity_type = serializers.JSONField()

    def to_internal_value(self, data):
        data = super().to_internal_value(data)
        for field_name in self.fields:
            value = data.get(field_name)
            if isinstance(value, str):
                data[field_name] = value.strip()

        return data
    class Meta:
        model = Quantity
        fields = ['quantity_name', 'quantity_name_en', 'sei_id', 'quantity_symbol', 'quantity_abbreviation','quantity_type',
                  'dimension', 'quantity_description', 'quantity_description_en', 'quantity_comment']


    def validate(self, attrs):
        if "dimension" in attrs:
            if len(attrs["dimension"]) == 0:
                attrs.pop("dimension")
            else:
                attrs["dimension"] = attrs["dimension"][0]
        if "quantity_type" in attrs:
            if len(attrs["quantity_type"]) == 0:
                attrs.pop("quantity_type")
            else:
                attrs["quantity_type"] = attrs["quantity_type"][0]
        try:
            attrs = super().validate(attrs)
        except serializers.ValidationError as e:
            raise serializers.ValidationError(str(e))
        return attrs


class QuantityInfoSerializer(serializers.ModelSerializer):
    quantity_type = serializers.SerializerMethodField()
    dimension = serializers.SerializerMethodField()
    available_units = serializers.SerializerMethodField()
    create_person = serializers.SerializerMethodField()
    modify_person = serializers.SerializerMethodField()

    class Meta:
        model = Quantity
        fields = ['quantity_name', "quantity_name_en", 'sei_id', 'quantity_symbol','quantity_abbreviation', 'quantity_type',
                  'dimension','available_units', 'quantity_description', 'quantity_description_en', 'quantity_comment', 'create_person', 'create_date', 'modify_person', 'modify_date']

    def get_quantity_type(self, obj):
        from ..config.type_config import QuantityType
        quantity_type_map = {}  
        for tag in QuantityType:
            quantity_type_map[tag.name] = tag.value
        return get_value_from_map(obj.quantity_type, quantity_type_map)

    def get_dimension(self, obj):
        return obj.dimension.show_short_name()

    def get_create_person(self, obj):
        return obj.create_person.user_name

    def get_modify_person(self, obj):
        return obj.modify_person.user_name
    
    def get_available_units(self, obj):
        unit_content = []
        unit_list = get_units_by_quantity(obj)
        for unit in unit_list:
            unit_content.append("{}({})".format(
                unit.show_short_name(), unit.unit_symbol))
        return " \n ".join(unit_content)


    @classmethod
    def get_extra_fields_info(self):
        return [{"dataIndex": "available_units", "title": "可用单位", "type": "TextField"},]
